<template>
    <view class="rx-button-edit" v-if="!readOnly">
        <rx-boxs v-model="curVal" @select="showDialog" @buttonSelect="buttonSelect" :read-only="readOnly"
                 :single="single" :icon="icon" :type="'btnEdit'" buttonedit="true"></rx-boxs>
    </view>
    <view v-else class="rx-disabled">
        {{ getValue(this.curVal) }}
    </view>
</template>

<script>
/**
 * 单值编辑按钮
 */
import MForm from "../js/MForm";
import RxBoxs from "../../form/common/RxBoxs.vue";
import FormBoListPreview from "../../form/formBoList/FormBoListPreview.vue";
import Dialog from "@/js/Dialog.js";
import baseButtonFunc from "@/js/baseButtonFunc.js"
import CustomQuery from "@/views/modules/form/customForm/js/CustomQuery.js";
import {FormApi} from "@/api/FormApi.js";

export default {
    name: "MButtonEditSingle",
    mixins: [MForm, baseButtonFunc],
    components: {
        RxBoxs,
        FormBoListPreview
    },
    data() {
        return {
            confJson: {},
            returnFields: {},
            isMain: true,
            gridName: "",
            defaultVal: "",
            single: true,
            curVal: "",
            icon: ''
        }

    },
    created() {
        if (this.metadata.options.dialogConfig) {
            let dialogConfig = JSON.parse(this.metadata.options.dialogConfig);
            this.single = dialogConfig.singleType == 'single' ? true : false;
        }
        this.icon = this.metadata.options.checkedChildren ? this.metadata.options.checkedChildren : '';
        this.initValue(this.value);
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "formLang", key);
        },
        getValue(value) {
            if (value) {
                let val = new Function("return " + value)();
                return val.label;
            }
            return ''
        },
        //判断是否要清空子表
        buttonSelect(idx) {
            this.curVal = idx;
            this.setData(this.curVal);
        },
        //打开对话框。
        showDialog() {
            let binding = JSON.parse(this.metadata.options.dialogConfig);
            if (binding.beforeMethod && this.isBeforeMethod(binding.beforeMethod)) {
                return;
            }
            //对话框
            if (!binding || !binding.dialogAlias || !JSON.parse(binding.dialogAlias).value) {
                uni.showToast({
                    title: this.i18n('boundDialog', '没有绑定对话框'), // 消息内容
                    duration: 1500, // 持续时间（单位：毫秒）
                    icon: 'none' // 图标类型（可选值：success/loading/none）
                });
                return;
            }
            var dialogAlias = JSON.parse(binding.dialogAlias).value;
            var gridInput = binding.gridInput;
            /*如果输入条件有必填，则提示*/
            if (this.isConditionRequired(gridInput, this.formVm.data, this.data)) {
                return;
            }
            //构建查询条件。
            var params = CustomQuery.getParamsInput(gridInput, this.globalData, this.data);
            params = Object.keys(params).map(function (key) {
                return key + "=" + params[key];
            }).join("&");
            let self_ = this;
            let initData = this.getInitData();
            let conf = {
                data: {
                    alias: dialogAlias,
                    single: this.single,
                    params: params,
                    pmtAlias: binding.pmtAlias,
                },
                curVm: this,
            };
            if (initData) {
                conf.data.initData = initData;
            }
            Dialog.openDialog(conf, function (data) {
                if (data.action == "ok") {
                    let dialogConfig = JSON.parse(self_.metadata.options.dialogConfig);
                    //绑定映射行
                    self_.bindRows(dialogConfig, data.data.rows);
                    self_.handBindSelf(dialogConfig, data.data.rows);
                    if (dialogConfig.callback) {
                        self_.formVm[dialogConfig.callback]({rows: data.data.rows});
                    }
                }
            })
        },
        /**
         * 绑定当前控件
         * @param binding
         * @param rows
         */
        handBindSelf(binding, rows) {
            let textField = binding.textField;
            let valueField = binding.useCondSql == 'WEBREQ' || binding.useCondSql == 'INTERFACE' ? binding.valueField : binding.valueField.toUpperCase();
            let aryText = [];
            let aryValue = [];
            for (let i = 0, j = rows.length; i < j; i++) {
                let row = rows[i];
                let value = row[valueField];
                let text = this.getText(binding, textField, row);
                aryValue.push(value);
                aryText.push(text);
            }
            let newVal = {label: aryText.join(","), value: aryValue.join(",")};
            this.curVal = JSON.stringify(newVal);
            this.setData(this.curVal)
        },
        getText(binding, options, row) {
            let format = binding.format
            for (let i = 0; i < options.length; i++) {
                let filed = options[i];
                let text = row[filed];
                let toReplace = "{" + filed + "}";
                format = format.replaceAll(toReplace, text);
            }
            return format;
        },
        initValue(val) {
            if (!val) return;
            if (!val.includes('{')) {
                if (this.metadata.options && this.metadata.options.dialogConfig) {
                    FormApi.getBtnEditSingleValue({
                        config: this.metadata.options.dialogConfig,
                        value: val
                    }).then(res => {
                        if (res.success && res.data) {
                            this.curVal = res.data;
                            this.updateValue(this.curVal);
                        }
                    });
                }
            } else {
                this.curVal = val;
            }
        },
        /**
         * 根据选择的数据构造初始化数据.
         * @returns {{keyField, selected}|null}
         */
        getInitData() {
            if (!this.curVal) {
                return null;
            }
            let json = JSON.parse(this.curVal);
            if (!json.value) {
                return null;
            }
            let binding = JSON.parse(this.metadata.options.dialogConfig);
            let valueField = binding.valueField;
            return {
                keyField: valueField,
                selected: json.value.split(",")
            }
        },
    },
    watch: {
        value: {
            handler(val, oldVal) {
                if (val) {
                    this.initValue(val);
                } else {
                    this.curVal = '';
                }
            },
            deep: true
        }
    }
}
</script>

<style scoped>
.rx-disabled {
    background: rgba(245, 246, 249, 1);
    display: flex;
    align-items: center;
    padding: 0.5rem;
    border-radius: 4px;
    border: none;
    min-height: 1rem;
}
</style>
